from . import passport_blu
from flask import  current_app , jsonify
from info.utils.captcha.captcha import captcha
from info import constants
from info.utils.response_code import  RET,error_map
from info import redies_store, db
from flask import request, session
from flask import make_response, abort
import re
import logging
import random
from info.models import User
import datetime


@passport_blu.route("/login", methods=['POST'])
def Login():
    print("------------in login ----------------")
    reciveData = request.json
    print("recive data :", reciveData)
    mobile = reciveData.get("mobile")
    password = reciveData.get("password")

    if not all([mobile, password]):
        return jsonify(errno=RET.DATAERR, errmsg="请正确输入账号和密码")

    # 根据用户名查找数据库

    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    if not user:
        return jsonify(errno=RET.DATAERR, errmsg="用户不存在")

    # 验证密码
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR, errmsg="密码错误")

    #保存用户状态
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile

    # 记录用户最后一次登录时间
    user.last_login = datetime.datetime.now()
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)

    return jsonify(errno=RET.OK, errmsg="OK")


@passport_blu.route("/register", methods=['POST'])
def RegisTer():
    print("------------ in grester -----------")
    print("requst mothor is ", request.method)

    reciveData = request.json
    print("recive data :",  reciveData)
    mobile = reciveData.get("mobile")
    smscode = reciveData.get("smscode")
    password = reciveData.get("password")

    # 根据电话号码到redis里获取验证码
    try:
        real_smcode = redies_store.get("SMS_" + mobile)
        if real_smcode:
            real_smcode = real_smcode.decode()
            redies_store.delete("SMS_" + smscode)
    except Exception as r:
        logging.error(r)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")

    # 比较验证码与传入的验证码是否相同
    if not real_smcode:
        return jsonify(errno=RET.DATAERR, errmsg="验证码已过期")

    if real_smcode != smscode:
        print("real_smcode type is", type(real_smcode))
        print("real_smcode is", real_smcode)
        print("smscode type is ", type(smscode))
        print("smscode is ",   smscode)

        return jsonify(errno=RET.DATAERR, errmsg="验证码错误")

    # 将用户注册到到数据表中

    user = User()
    user.mobile = mobile
    user.password = password
    user.nick_name = mobile

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as r:
        db.session.rollback()
        logging.error(r)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")

    # 将用户保存到session，保持登录状态
    # 5. 保存用户登录状态
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile


    return jsonify(errno=RET.OK, errmsg="OK")



@passport_blu.route("/cert_code", methods=['POST'])
def GetCertCode():
    """
    1.获取参数并解析
    2.检查图片验证码内容是否正确或者是否过期
    3.检查手机号码格式
    4.生成短信验证码
    5.请求第三方短信平台转发短信
    6.将验证码内容保存到哦redis中
    :return:
    """

    print("-------------- in get cert_code------------------")
    print("requset metho is ", request.method)
    print("recive args data: ", request.args)
    # print("recive forms data", request.form)
    print("recive jason:", request.json)

    requesData = request.json
    image_id = requesData.get('imageCodeId')
    image_code = requesData.get('imageCode')
    mobile=requesData.get('mobile')
    print("get  mobile:%s image_id:%s image_code%s" % (mobile, image_id, image_code))

    respond  = {"errno": "", "errmsg": ""}

    if not all([mobile, image_id, image_code]):
        # 参数不全
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

        # 2. 校验手机号是正确
    if not re.match("^1[3578][0-9]{9}$", mobile):
        # 提示手机号不正确
        return jsonify(errno=RET.DATAERR, errmsg="手机号不正确")

    try:
        real_imageCode  = redies_store.get("imageCode"+image_id)
        if real_imageCode:
            real_imageCode = real_imageCode.decode()
            redies_store.delete("imageCode"+image_id)
    except Exception as r:
        logging.error(r)
        respond["errno"] = r
        respond["errmsg"] = "获取图片验证码失败"
        return jsonify(**respond)

    if not real_imageCode:
        return jsonify(errno=RET.DATAERR, errmsg= "验证码已过期")

    if real_imageCode != image_code:
        return jsonify(errno=RET.DATAERR, errmsg="图片验证码错误")

    # 调用生成随机数验证码
    result = random.randint(0, 999999)
    sms_code = "%06d" % result
    print("随机数验证码：", sms_code)

    # 调用第三方短信平台发送 Todo

    # 将验证码保存到redisl里
    try:
        redies_store.set("SMS_"+mobile, sms_code, ex=120)
    except Exception as r:
        logging.error(r)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作错误")

    return jsonify(errno=RET.OK, errmsg="验证码已发送")




@passport_blu.route("/image_code")
def GetImageCode():
    """
    1.返回图片验证码
    :return:
    """
    print("---------------in get image_code----------------")
    # 获取参数
    image_code_id = request.args.get("code_id", None)
    if not image_code_id:
        return abort(403)
    # 生成图片验证码
    imageName, imageText, imageData = captcha.generate_captcha()
    # 保存到redis
    try:
        redies_store.set("imageCode"+image_code_id, imageText, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as r:
        logging.error(r)
        return abort(500)
    # 返回图片
    response = make_response(imageData)
    response.headers["Content-Type"] = "image/jpg"
    return response